package com.example.appointment.controller;

import com.example.appointment.annotation.RequireRole;
import com.example.appointment.dto.ActivityRegistrationDTO;
import com.example.appointment.dto.ClubActivityDTO;
import com.example.appointment.service.ActivityRegistrationService;
import com.example.appointment.service.ClubActivityService;
import com.example.appointment.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社团活动控制器
 */
@RestController
@RequestMapping("/api/activities")
public class ClubActivityController {

    @Autowired
    private ClubActivityService activityService;
    
    @Autowired
    private ActivityRegistrationService registrationService;
    
    /**
     * 获取活动列表（分页）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getActivities(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "startTime") String sortBy,
            @RequestParam(defaultValue = "asc") String direction) {
        
        Sort sort = "desc".equalsIgnoreCase(direction) ?
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
        
        Pageable pageable = PageRequest.of(page, size, sort);
        Long currentUserId = UserUtils.getCurrentUserId();
        
        Page<ClubActivityDTO> activitiesPage = activityService.getActiveActivities(pageable, currentUserId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("activities", activitiesPage.getContent());
        response.put("currentPage", activitiesPage.getNumber());
        response.put("totalItems", activitiesPage.getTotalElements());
        response.put("totalPages", activitiesPage.getTotalPages());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 搜索活动
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchActivities(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Long currentUserId = UserUtils.getCurrentUserId();
        
        Page<ClubActivityDTO> activitiesPage = activityService.searchActivities(keyword, pageable, currentUserId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("activities", activitiesPage.getContent());
        response.put("currentPage", activitiesPage.getNumber());
        response.put("totalItems", activitiesPage.getTotalElements());
        response.put("totalPages", activitiesPage.getTotalPages());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取活动详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<ClubActivityDTO> getActivityById(@PathVariable Long id) {
        Long currentUserId = UserUtils.getCurrentUserId();
        ClubActivityDTO activity = activityService.getActivityById(id, currentUserId);
        return ResponseEntity.ok(activity);
    }
    
    /**
     * 创建新活动（仅管理员可用）
     */
    @PostMapping
    @RequireRole({"ADMIN"})
    public ResponseEntity<ClubActivityDTO> createActivity(@Valid @RequestBody ClubActivityDTO activityDTO) {
        Long currentUserId = UserUtils.getCurrentUserId();
        ClubActivityDTO createdActivity = activityService.createActivity(activityDTO, currentUserId);
        return ResponseEntity.ok(createdActivity);
    }
    
    /**
     * 更新活动信息（仅管理员可用）
     */
    @PutMapping("/{id}")
    @RequireRole({"ADMIN"})
    public ResponseEntity<ClubActivityDTO> updateActivity(
            @PathVariable Long id,
            @Valid @RequestBody ClubActivityDTO activityDTO) {
        
        ClubActivityDTO updatedActivity = activityService.updateActivity(id, activityDTO);
        return ResponseEntity.ok(updatedActivity);
    }
    
    /**
     * 取消活动（仅管理员可用）
     */
    @PostMapping("/{id}/cancel")
    @RequireRole({"ADMIN"})
    public ResponseEntity<Void> cancelActivity(@PathVariable Long id) {
        activityService.cancelActivity(id);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 删除活动（仅管理员可用）
     */
    @DeleteMapping("/{id}")
    @RequireRole({"ADMIN"})
    public ResponseEntity<Void> deleteActivity(@PathVariable Long id) {
        activityService.deleteActivity(id);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 用户报名活动
     */
    @PostMapping("/{id}/register")
    public ResponseEntity<ActivityRegistrationDTO> registerForActivity(@PathVariable Long id) {
        Long currentUserId = UserUtils.getCurrentUserId();
        ActivityRegistrationDTO registration = registrationService.registerForActivity(id, currentUserId);
        return ResponseEntity.ok(registration);
    }
    
    /**
     * 取消活动报名
     */
    @DeleteMapping("/{id}/register")
    public ResponseEntity<Void> cancelRegistration(@PathVariable Long id) {
        Long currentUserId = UserUtils.getCurrentUserId();
        registrationService.cancelRegistration(id, currentUserId);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 提交活动评价
     */
    @PostMapping("/{id}/feedback")
    public ResponseEntity<ActivityRegistrationDTO> submitFeedback(
            @PathVariable Long id,
            @RequestParam String feedback,
            @RequestParam(required = false) Integer rating) {
        
        Long currentUserId = UserUtils.getCurrentUserId();
        ActivityRegistrationDTO updatedRegistration = 
                registrationService.submitFeedback(id, currentUserId, feedback, rating);
        
        return ResponseEntity.ok(updatedRegistration);
    }
    
    /**
     * 获取活动的评价列表
     */
    @GetMapping("/{id}/feedbacks")
    public ResponseEntity<List<ActivityRegistrationDTO>> getActivityFeedbacks(@PathVariable Long id) {
        List<ActivityRegistrationDTO> feedbacks = registrationService.getActivityFeedbacks(id);
        return ResponseEntity.ok(feedbacks);
    }
    
    /**
     * 获取用户的活动报名列表
     */
    @GetMapping("/my-registrations")
    public ResponseEntity<List<ActivityRegistrationDTO>> getUserRegistrations() {
        Long currentUserId = UserUtils.getCurrentUserId();
        List<ActivityRegistrationDTO> registrations = registrationService.getUserRegistrations(currentUserId);
        return ResponseEntity.ok(registrations);
    }
} 